import { useState, useContext, useEffect } from "react";
import { useNavigate } from "react-router-dom"
import { UserContext } from "../context/userContext"
import axios from 'axios';
import "./login.css"
import {Dialog, DotLoading, Modal, Result, Toast} from "antd-mobile";

const Forget = () => {
  const {setCurrentUser} = useContext(UserContext)
  const navigate = useNavigate()
  const [userData, setUserData] = useState({
    email: '',
    password: '',
  });
  const sleep = (time) =>
      new Promise(resolve => setTimeout(resolve, time))
  const changeInputHandler = (e) => {
    e.preventDefault();
    setUserData(prevState => {
      return { ...prevState, [e.target.name]: e.target.value };
    });
  };
  const forgetUser = async (e) => {
    e.preventDefault();
    setError('');
    try {
      const response = await axios.post(`${process.env.REACT_APP_BASE_URL}/users/forget`, userData);
      if(response.status === 200) {
        await Dialog.confirm({
          confirmText:'重新发送',
          cancelText:'明白',
          content: (<Result
              status='success'
              icon={<div className="image-wrapper_email flex-col">
                <img
                    className="label_email"
                    src={"https://lanhu-oss.lanhuapp.com/FigmaDDSSlicePNGfdd075f71013104dcdd4908a86c58f5b.png"}
                />
              </div>}
              title='已发送重置电子'
              description={`我们刚刚向${userData.email}发送了一封带有密码重置链接的电子邮件.`}
          />),
          onConfirm: async () => {
            await sleep(3000)
            const response = await axios.post(`${process.env.REACT_APP_BASE_URL}/users/forget`, userData);
            if(response.status === 200) {
              Toast.show({
                icon: 'success',
                content: '重新发送成功',
                position: 'bottom',
              })
              navigate('/login');
            }
          }
        });
      }

      setCurrentUser(null);

    } catch (err) {
      setError(err.response.data.message);
    }
  };

  const [error, setError] = useState('');
  return (
      <section className="login">
        <div className="text-group_1 flex-col justify-between">
          <span className="text_3">忘记密码？</span>
          <span className="text_4">请输入您的电子邮件地址以继续</span>
        </div>
        <form className="form login__form" onSubmit={forgetUser}>
          {error && <p className="form__error-message">{error}</p>}
          <div className="box_3 flex-row justify-between">
            <div className="image-wrapper_1 flex-col">
              <img
                  className="label_2"
                  src={"https://lanhu-oss.lanhuapp.com/FigmaDDSSlicePNGbe33209837fd2b314332d897e7b9d0a5.png"}
              />
            </div>
            <div className="text-group_2 flex-col justify-between">
              <span className="text_5">邮箱</span>
              <input className="text_8" type="text" placeholder="请输入您的邮箱号" name="email" value={userData.email}
                     onChange={changeInputHandler}
                     autoFocus/>
            </div>
          </div>
          <div className="text-wrapper_3 flex-col">
            <button type="submit" className="text_11">继续</button>
          </div>
        </form>
      </section>
  )
}

export default Forget
